# Copyright (c) 2025 Huawei Technologies Co. Ltd.
# deepinsight is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
from deepinsight.config.logger import get_logger
from deepinsight.stores.mongodb.database import MongoDB
logger = get_logger(__name__)


class SessionManager:
    """浏览器Session管理"""

    @staticmethod
    async def verify_user(session_id: str) -> bool:
        """验证用户是否在Session中"""
        try:
            collection = MongoDB().get_collection("session")
            data = await collection.find_one({"_id": session_id})
            if not data:
                return False
            return data.get("user_sub") is not None
        except Exception as e:
            err = "用户不在Session中"
            logger.error("[SessionManager] %s", err)
            raise e

    @staticmethod
    async def get_user_sub(session_id: str) -> str:
        """从Session中获取用户"""
        try:
            collection = MongoDB().get_collection("session")
            data = await collection.find_one({"_id": session_id})
            if not data:
                return None
            user_sub = data.get("user_sub")
        except Exception as e:
            err = "从Session中获取用户失败"
            logger.error("[SessionManager] %s", err)
            raise e

        return user_sub